package com.yimi.yinhepda.net;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.callbacks.QueryMacUICallBack;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.request.QueryMacAddressRequest;
import com.yimi.yinhepda.entity.response.QueryCheckMacEnableResponse;
import com.yimi.yinhepda.entity.response.QueryMacAddressResponse;
import com.pda.ym.utils.Constants;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SoundVibratorManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 校验和查询可用的mac地址
 *
 * @author Administrator
 * @date 2018/6/8 0008
 */

public class QueryMacNetRequest {

    /**
     * 分拨编码
     */
    private String deptCode;

    /**
     * 调用数据字典，查询mac校验是否开启
     */
    public QueryMacNetRequest checkAPMacEnable(final Context context, final QueryMacUICallBack callBack) {
        Map<String, String> params = new HashMap<>();
        params.put("params", "clock_mac");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_DICT_VALUE)
                .setParams(params)
                .setResponsClazz(QueryCheckMacEnableResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        callBack.onError(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof QueryCheckMacEnableResponse) {
                            QueryCheckMacEnableResponse response = (QueryCheckMacEnableResponse) obj;
                            QueryCheckMacEnableResponse.Data data = response.getData();
                            QueryCheckMacEnableResponse.ClockMac clockMac = data.getClock_mac();
                            if (clockMac == null) {
                                callBack.onError("打卡MAC校验未配置");
                                return;
                            }
                            String enable = clockMac.getEnable();
                            if (enable.equals("是")) {
                                //校验mac地址
                                checkAPMacAddress(context, callBack);
                            } else {
                                //无需校验
                                callBack.onSuccess();
                            }
                        } else {
                            callBack.onError("mac校验数据获取失败！");
                        }
                    }
                });
        return this;
    }

    /**
     * 拉取服务端维护的mac
     */
    public QueryMacNetRequest checkAPMacAddress(final Context context, final QueryMacUICallBack callBack) {
        if (deptCode == null) {
            SoundVibratorManager.playSound(2);
            callBack.onError("分拨编码为空！");
            return this;
        }
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        //获取被连接网络的mac地址
        final String netMac = wifiInfo.getBSSID();
        if (netMac == null) {
            SoundVibratorManager.playSound(2);
            callBack.onError(null);
            showCnnectFailWifiDialog(context);
            return this;
        }
        LogUtil.e("netMac=" + netMac);
        QueryMacAddressRequest macAddressRequest = new QueryMacAddressRequest();
        macAddressRequest.setDeptCode(deptCode);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryMacAddressResponse.class)
                .setUrl(Constants.URL_QUERY_MAC_ADDRESS)
                .setRequestObject(macAddressRequest)
                .setConnTimeOut(5 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        callBack.onError(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof QueryMacAddressResponse) {
                            QueryMacAddressResponse response = (QueryMacAddressResponse) obj;
                            List<QueryMacAddressResponse.MacAddressEntity> macAddressEntityList = response.getData();
                            boolean hasMac = false;
                            for (QueryMacAddressResponse.MacAddressEntity entity : macAddressEntityList) {
                                String[] netMacAddress = entity.getMacAddress().split(":");
                                String queryNetMac = "";
                                if (netMacAddress.length > 3) {
                                    queryNetMac = netMacAddress[0] + ":" + netMacAddress[1] + ":" + netMacAddress[2];
                                }
                                String[] localMacAddress = netMac.split(":");
                                String localMac = "";
                                if (localMacAddress.length > 3) {
                                    localMac = localMacAddress[0] + ":" + localMacAddress[1] + ":" + localMacAddress[2];
                                }
                                //比较apMac前三段是否相等
                                LogUtil.e("localMac=" + localMac);
                                LogUtil.e("queryNetMac=" + queryNetMac);
                                if (localMac.equalsIgnoreCase(queryNetMac)) {
                                    hasMac = true;
                                    break;
                                }
                            }
                            if (hasMac) {
                                //匹配到正确的mac地址
                                callBack.onSuccess();
                            } else {
                                callBack.onError(null);
                                //没有匹配到正确的mac地址,提示用户
                                showCnnectFailWifiDialog(context);
                            }
                        } else {
                            callBack.onError("mac获取数据失败！");
                        }
                    }
                });
        return this;
    }

    /**
     * 提示连接正确的分拨wifi
     */
    private void showCnnectFailWifiDialog(final Context context) {
        SoundVibratorManager.playSound(2);
        MyDialog dialog = new MyDialog(context);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("提示");
        dialog.setMessage("对不起！您当前所处网络状态下无法进行打卡操作，请链接分拨WIFI进行打卡！");
        dialog.setPositiveClickListener("设置WIFI", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
                context.startActivity(intent);
            }
        });
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "返回", null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    public String getDeptCode() {
        return deptCode;
    }

    public QueryMacNetRequest setDeptCode(String deptCode) {
        this.deptCode = deptCode;
        return this;
    }
}
